
# Execute R code to generate Figure 6.
# Baron et. al (2024), Forthcoming, Political Behavior
# Couples Therapy for a Divided America: 
# Assessing the Effects of Reciprocal Group Reflection # on Partisan Polarization


rm(list=ls()) 
library(readxl) # library to read in excel spreadsheet of dedoose data
library(tidyverse) # library for mutating data
library(ggplot2)

pathdata <- "INSERT WORKING DIRECTORY PATH HERE"
setwd(pathData)
getwd()


cleaned_data <- read_excel("qualdata.xlsx") # load in data from local directory


# FIGURE 5

# simple frequency graph of all codes

# get counts for all variables by turning dataframe into table
dd_counts <- cleaned_data[, 7:30]
table_list <- lapply(dd_counts, table)
var_names <- names(table_list) # pull out variable names

library(data.table) # library to convert individual table counts into a single table
table_counts <- rbindlist(lapply(table_list, as.data.frame.list), fill=TRUE) # combine counts into one table
count_df <- as.data.frame(table_counts) # convert table to df
count_df <- cbind(var_names, count_df) # add back variable names to corresponding counts
names(count_df)[2] <- "False"
names(count_df)[3] <- "True"
count_df$True[which(is.na(count_df$True))] <- 0

# simple frequency graph of mechanisms ONLY

# remove columns that don't have EPE tag applied
subset_counts <- cleaned_data %>% 
  dplyr::select(18, 21, 34, 36, 38, 40, 42, 46)

subset_counts <- subset_counts %>% 
  summarise_all(funs(sum(.==1)))

subset_counts$group_salience <- subset_counts$ingroup_heterogeneity + subset_counts$group_identity_pos

### Generate counts
subset_counts <- subset_counts %>%
  dplyr::select(2, 3, 4, 5, 6, 7, 9)

colnames(subset_counts)[1] <- "Individual Ideological Statement"
colnames(subset_counts)[2] <- "Perceived Mass Polarization"
colnames(subset_counts)[3] <- "Empathy to Outgroup"
colnames(subset_counts)[4] <- "Humanization of Outgroup"
colnames(subset_counts)[5] <- "Moralization of Politics"
colnames(subset_counts)[6] <- "Stereotyping"
colnames(subset_counts)[7] <- "Group Identity Salience"

# transpose df
subset_counts = t(subset_counts)
subset_counts <- as.data.frame(subset_counts, keep.rownames = T)
names(subset_counts)[1] <- "Frequency"
subset_counts <- rownames_to_column(subset_counts, "tag")

labeling <- c("Individual \nIdeological Statement","Perceived Mass\nPolarization", "Empathy to\nOutgroup", "Group Identity\nSalience", "Humanization\nof Outgroup", "Moralization\nof Politics", "Stereotyping")

# plot counts
ggplot(data=subset_counts, aes(x=reorder(tag, -Frequency), y=Frequency)) +
  geom_bar(stat="identity", fill="steelblue")+
  geom_text(aes(label=Frequency), vjust=-0.3, size=3.5)+
  theme(axis.text.x = element_text(vjust = 1)) +
  scale_x_discrete(labels = labeling) +
  xlab("") +
  ylab("") +
  theme_minimal()

ggsave("qual_mechanisms.pdf", width=8, height=6)

